package org.xawl.news.servlet.user;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.xawl.news.dao.impl.role.RoleDaoImpl;
import org.xawl.news.dao.impl.user.UserDaoImpl;
import org.xawl.news.dao.role.RoleDao;
import org.xawl.news.dao.user.UserDao;
import org.xawl.news.entity.role.Role;
import org.xawl.news.entity.user.User;
import org.xawl.news.servlet.base.BaseServlet;
import org.xawl.news.util.AjaxJson;
import org.xawl.news.util.MD5Util;

import com.alibaba.fastjson.JSON;

public class UserServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	
	private UserDao userDao = new UserDaoImpl();
	private RoleDao roleDao = new RoleDaoImpl();
	
	protected String list(HttpServletRequest request, HttpServletResponse response) {
		List<User> users = userDao.findList();
		int count = userDao.findCout();
		request.setAttribute("users", users);
		request.setAttribute("count", count);
		return "forward:system/user/userList";
	}
	
	/**
	 * 
	 * @Title: userAdd 
	 * @Description: 跳转至新增页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 * @return: String
	 */
	protected String add(HttpServletRequest request, HttpServletResponse response) {
		List<Role> roles = roleDao.findList();
		request.setAttribute("roles", roles);
		return "forward:system/user/userAdd";
	}
	
	protected void save(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AjaxJson j = new AjaxJson();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String gender = request.getParameter("gender");
		String major = request.getParameter("major");
		String classes = request.getParameter("classes");
		String grade = request.getParameter("grade");
		String mobile = request.getParameter("mobile");
		String email = request.getParameter("email");
		String roleId = request.getParameter("roleId");
		User user = new User();
		user.setUsername(username);
		user.setPassword(MD5Util.MD5Encode(password, "UTF-8").toUpperCase());
		if("on".equalsIgnoreCase(gender)) {
			user.setGender(1);
		} else {
			user.setGender(0);
		}
		user.setMajor(major);
		user.setClasses(classes);
		user.setGrade(grade);
		user.setMobile(mobile);
		user.setEmail(email);
		user.setIsEnabled(0);
		user.setCreateTime(new Date());
		user.setUpdateTime(new Date());
		user.setRoleId(Integer.valueOf(roleId).intValue());
		boolean flag = userDao.save(user);
		if(flag) {
			j.setMsg("添加用户成功!");
			j.setSuccess(true);
		} else {
			j.setMsg("添加用户失败!");
			j.setSuccess(false);
		}
		response.getWriter().write(JSON.toJSONString(j));
	}

}
